package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private BlogMapper blogMapper;

    @Resource
    private FollowMapper followMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = blogMapper.queryById(id);
        if(Objects.isNull(blog)){
            return Result.fail("该Blog不存在...");
        }
        queryBlogUser(blog);
        return Result.ok(blog);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(this::queryBlogUser);
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        //查询redis是否点赞过
        String key = "blog:like:"+id;
        UserDTO user = UserHolder.getUser();
        String userId = user.getId().toString();
        Double score = redisTemplate.opsForZSet().score(key, userId);
        /*
            score 为 null，说明用户没有点赞过
         */
        if(!Objects.isNull(score)){
            //该用户已经点赞过
            boolean success = blogMapper.updateLiked(-1, id);
            if(success){
                redisTemplate.opsForZSet().remove(key,userId);
            }
        }else {
            //该用户没有点赞过
            boolean success = blogMapper.updateLiked(1, id);
            if(success){
                redisTemplate.opsForZSet().add(key,userId,System.currentTimeMillis());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikesTop5(Long id) {
        String key = "blog:like:"+id;
        Set<String> userIdsStr = redisTemplate.opsForZSet().range(key, 0, 4);
        if(Objects.isNull(userIdsStr)||userIdsStr.size() == 0){
            return Result.ok(Collections.emptyList());
        }
        List<Long> userIds = userIdsStr.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> dtoList = userMapper.queryByIds(userIds).stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(dtoList);
    }

    @Override
    public Result queryBlogByUserId(Integer current, Long id) {
        // 根据用户查询
        Page<Blog> page = query()
                .eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        blog.setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now());
        // 保存探店博文
        boolean success = blogMapper.insertRecord(blog);
        //boolean success = save(blog);//TODO:为啥使用save之后，id就有了。。https://blog.csdn.net/geinvse_seg/article/details/123671321
        if(!success){
            return Result.fail("添加博文失败!");
        }
        //查询该用户所有粉丝
        List<Follow> follows = followMapper.queryAllByFollowUserId(user.getId());
        //将博文推送到粉丝的收件箱
        follows.stream().parallel().forEach(follow -> {
            Long followId = follow.getUserId();//获取粉丝Id
            redisTemplate.opsForZSet().add("feed:"+followId,blog.getId().toString(),System.currentTimeMillis());
        });
        // 返回id
        return Result.ok(blog.getId());
    }

    @SuppressWarnings("ConstantConditions")
    @Override
    public Result queryFollowBlog(Long max, Integer offset) {
        UserDTO user = UserHolder.getUser();
        String key = "feed:"+user.getId();
        //查询滚动分页数据   ZREVRANGEBYSCORE key Max min WithScore Limit offset count
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 3);
        if(Objects.isNull(typedTuples) || typedTuples.size() == 0){
            return Result.ok();
        }
        //解析数据：blogId、minTime（时间戳）、offset
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        int newOffSet = 1;
        long minTime = 0;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            //获取blogid
            String blogIdStr = tuple.getValue();
            blogIds.add(Long.valueOf(blogIdStr));
            //获取score  即时间戳
            long timestamp = tuple.getScore().longValue();
            newOffSet = timestamp == minTime?newOffSet+1:1;
            minTime = timestamp;
        }

        //根据 id 查blog
        List<Blog> blogList = blogMapper.queryByIds(blogIds);
        blogList.forEach(this::queryBlogUser);
        //封装结果对象
        ScrollResult scrollResult = ScrollResult.builder()
                .list(blogList).minTime(minTime).offset(newOffSet).build();
        return Result.ok(scrollResult);
    }

    private void queryBlogUser(Blog blog){
        Long userId = blog.getUserId();
        User user = userMapper.queryById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        //设置该用户是否点赞过
        UserDTO loginUser = UserHolder.getUser();
        if(Objects.isNull(loginUser)){
            //如果用户未登录，就不设置是否点赞过了。
            return;
        }
        String key = "blog:like:"+blog.getId();
        String userIdStr = loginUser.getId().toString();
        Double score = redisTemplate.opsForZSet().score(key,userIdStr);
        blog.setIsLike(!Objects.isNull(score));
    }
}
